﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public partial class frmEditGridCellValue : Form
    {
        private ExcelWorkLogService _service;
        private ExcelWorkLogGrid _grid;

        public frmEditGridCellValue(ExcelWorkLogService service, ExcelWorkLogGrid grid, string[] forbiddenCols)
        {
            InitializeComponent();

            if (service == null)
                throw new ArgumentNullException("service");

            if (grid == null)
                throw new ArgumentNullException("grid");

            _service = service;
            _grid = grid;

            LoadAvailableColumnNames(forbiddenCols ?? new string[0]);
        }

        private void LoadAvailableColumnNames(string[] forbiddenCols)
        {
            cboxColumnName.SuspendLayout();

            for (int i = 0; i < _grid.Columns.Count; i++)
            {
                var col = _grid.Columns[i];
                if (col.Visible == false)
                    continue;

                if (forbiddenCols.Contains(col.Name))
                    continue;

                cboxColumnName.Items.Add(col.Name);
            }

            cboxColumnName.ResumeLayout();
            cboxColumnName.SelectedIndex = 0;
        }

        private void ReleaseAllReferences()
        {
            _service = null;
            _grid = null;
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            ReleaseAllReferences();
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var col = (string)cboxColumnName.SelectedItem;
            var rows = _grid.SelectedRows;
            var logs = new List<ExcelWorkLogItem>(rows.Count);

            for (int i = 0; i < rows.Count; i++)
            {
                rows[i].Cells[col].Value = txtNewValue.Text; // this will update boundedItem automically
                logs.Add((ExcelWorkLogItem)rows[i].DataBoundItem);
            }

            _service.Save(logs);

            ReleaseAllReferences();

            MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "编辑单元格操作",
                                Content = "保存成功！"
                            });

            this.Close();
        }
    }
}
